<template>
	<div class="clearfix">
		<a-upload
			v-model:file-list="fileList"
			:custom-request="customRequestAliyun"
			list-type="picture-card"
			@change="handleChange"
			@preview="handlePreview"
			:before-upload="beforeUpload"

		>
			<div v-if="fileList.length < limitImage && enable">
				<plus-outlined />上传
			</div>
		</a-upload>
		<a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
			<a-image alt="example" width="100%" :src="previewImage" />
		</a-modal>
	</div>
</template>
<script lang="ts" >
	import { UploadOutlined } from '@ant-design/icons-vue'
	import { message } from 'ant-design-vue'
	import { defineComponent, ref ,defineProps} from 'vue'
	import type  { UploadProps } from 'ant-design-vue'

	import fileApi from '@/api/dev/fileApi'


	function getBase64(file: File) {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = () => resolve(reader.result);
			reader.onerror = error => reject(error);
		});
	}

	export default defineComponent({
		components: {
			UploadOutlined
		},
		props: {
			limitImage: Number,
			enable:{
				type: Boolean,
				default: true
			}
		},
		setup(props) {
			const previewVisible = ref(false);
			const previewImage = ref('');
			const previewTitle = ref('');
			const limitImage=ref(props.limitImage);
			const enable=ref(props.enable);
			//地址路径解析
			const getFileName = (path) => {
				if (path.lastIndexOf('\\') >= 0) {
					let reg = new RegExp('\\\\', 'g')
					path = path.replace(reg, '/')
				}
				return path.substring(path.lastIndexOf('/') + 1)
			}
			//生成随机id
			const uidGenerator = () => {
				return '-' + parseInt(String(Math.random() * 10000 + 1), 10)
			}
			//构造通用附件对象
			const initFileInfo = (url) => {
				const name = getFileName(url)
				let itemValue = {
					uid: uidGenerator(),
					name: name,
					status: 'done',
					response: url,
					url: url
				}
				return itemValue
			}

			//回填上传数据列表
			const initFileList = (record) => {
				let paths = record
				if (!paths || paths.length === 0) {
					return 0
				}
				paths.split(',').forEach((item) => {
					let itemValue = initFileInfo(item.trim())
					fileList.value.push(itemValue)
				})
			}

			const fileList = ref<UploadProps['fileList']>([])

			const handleCancel = () => {
					previewVisible.value = false;
					previewTitle.value = '';
			};
			const handlePreview = async (file: UploadProps['fileList'][number]) => {
				if (!file.url && !file.preview) {
					file.preview = (await getBase64(file.originFileObj)) as string;
				}
				previewImage.value = file.url || file.preview;
				previewVisible.value = true;
				previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
			};

			const beforeUpload = file => {
				const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
				if (!isImg) {
					message.error('只能上传图片!');
				}
				return isImg;
			};

			// 上传阿里云文件
			const customRequestAliyun = (file) => {
				const fileData = new FormData()
				fileData.append('file', file.file)
				fileApi.fileUploadAliyunReturnUrl(fileData).then((res) => {
					file.onSuccess(res, file.file)
					file.status = 'done'
				})
			}

			const handleChange= (info) => {
				//这里判断文件是否上传成功
				if (info.file.status === 'done') {
					//判断是否正确链接上传地址
					//fileList.value.push(initFileInfo(info.file.response)
					//如果是移除文件也会重新填入selectFile
				} else if (info.file.status === 'removed') {
					//deleteFileItem(info.file)
				}
			}

			//组装路径
			const buildUrl = () => {
				if (fileList.value) {
					return fileList.value
						.map((x) => {
							return x.response
						})
						.join(',')
				} else {
					return ''
				}
			}
			return {
				fileList,
				handleChange,
				customRequestAliyun,
				previewVisible,
				previewImage,
				handleCancel,
				handlePreview,
				beforeUpload,
				previewTitle,
				initFileList,
				limitImage,
				buildUrl,
				enable

			}
		},
	})

</script>

<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
	font-size: 32px;
	color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
	margin-top: 8px;
	color: #666;
}
</style>
